﻿$.validator.addMethod('ajax', function (value, element, params) {
    if (!value || value == "") {
        return false;
	}
    else {
        var url = params["url"];
        var objParam = { "param1": value };
        var result = getAjaxValidate(url, objParam);
        return this.optional(element) || result;
	}
});

$.validator.unobtrusive.adapters.add("ajax", ["url"], function (options) {
    options.rules["ajax"] = {
        url: options.params.url
    };
    options.messages["ajax"] = options.message;
});

function getAjaxValidate(url, param) {
    var flag = false;
    $.ajax({
        type: "GET",
        async: false,
        cache: false,
        contentType: "application/json",
        url: url,
        data: param,
        dataType: 'json',
        headers: {
            "X-CSRF-TOKEN-JXWebHost": $("input[name='AntiforgeryFieldname']").val()
        },
        error: function (data, status, e) {
            flag = false;
        },
        success: function (returnData) {
            if (returnData.Status == 1) {
                flag = true;
            }
            else {
                flag = false;
            }
        }
    });
    return flag;
}

$.validator.addMethod('compare', function (value, element, params) {
    if (!value || value == "") {
        return false;
    }
    else {
        var other = params["other"];
        var operator = params["operator"];
        var ToCompare = $("#" + other).val();
        var result = getCompareValidate(value, ToCompare, operator);
        return this.optional(element) || result;
    }
});

$.validator.unobtrusive.adapters.add("compare", ["other","operator"], function (options) {
    options.rules["compare"] = {
        other: options.params.other
        ,operator: options.params.operator
    };
    options.messages["compare"] = options.message;
});
/**
 * 做比较验证
 * @param {any} ToValidate:要验证的值
 * @param {any} ToCompare:被比较的值
 * @param {any} Operator:比较类型(Equal,NotEqual,GreaterThan,GreaterThanEqual,LessThan,LessThanEqual)
 */
function getCompareValidate(ToValidate, ToCompare, Operator) {
    var flag = false;
    switch (Operator) {
        case "Equal"://相等
            flag = (ToValidate == ToCompare);
            break;
        case "NotEqual"://不相等
            flag = (ToValidate != ToCompare);
            break;
        case "GreaterThan"://大于
            flag = (parseFloat(ToValidate) > parseFloat(ToCompare));
            break;
        case "GreaterThanEqual"://大于等于
            flag = (parseFloat(ToValidate) >= parseFloat(ToCompare));
            break;
        case "LessThan"://小于
            flag = (parseFloat(ToValidate) < parseFloat(ToCompare));
            break;
        case "LessThanEqual"://小于等于
            flag = (parseFloat(ToValidate) <= parseFloat(ToCompare));
            break;
    }
    return flag;
}